package com.ssm.subject.domain.handler.subejct;

import com.ssm.subject.common.enums.SubjectInfoTypeEnum;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 题目类型工厂类
 */
@Component
public class SubjectTypeHandlerFactory implements InitializingBean {
    @Resource //可获取所有实现类(实现类要被加入到IOC容器)
    private List<SubejctTypeHandler> subejctTypeHandlerList;

    private Map<SubjectInfoTypeEnum, SubejctTypeHandler> subejctTypeHandlerMap = new HashMap<>();

    /**
     * 对外提供根据id获取对应的题目策略类
     * @param subjectType
     * @return
     */
    public SubejctTypeHandler getHandler(int subjectType) {
        SubjectInfoTypeEnum subjectInfoTypeEnum = SubjectInfoTypeEnum.getByCode(subjectType);
        return subejctTypeHandlerMap.get(subjectInfoTypeEnum);
    }

    /**
     * 实现InitializingBean后可重写该方法，实现当前bean初始化完成后执行该方法为handlerMap赋值
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        for (SubejctTypeHandler subjectTypeHandler : subejctTypeHandlerList) {
            subejctTypeHandlerMap.put(subjectTypeHandler.getHandlerType(), subjectTypeHandler);
        }
    }
}
